<template>
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-input class="w-50" v-model="form.tag_name" placeholder="标签名称"></el-input>
        <el-select
          v-model="form.tag_status"
          placeholder="标签状态"
          class="!w-[160px]"
          clearable
        >
          <el-option
            v-for="item in options['assignment.ImagesTag']?.[0].tagStatusText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="form.tag_type"
          class="!w-[160px]"
          placeholder="标签类型"
          clearable
        >
          <el-option
            v-for="item in options['assignment.ImagesTag']?.[0].tagTypeText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="form.permissions_type"
          class="!w-[160px]"
          placeholder="标签权限类型"
          clearable
        >
          <el-option
            v-for="item in options['assignment.ImagesTag']?.[0].permissionsTypeText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <select-personnel
          v-model="form.user_id"
          placeholder="标签权限指定人员"
        ></select-personnel>
        <el-input class="w-50" v-model="form.remark" placeholder="备注"></el-input>
      </template>
      <template #toolbar_btns>
        <VButton auth="/goods/basics/images-tag/add" type="primary" @click="open('add')"
          ><svg-icon icon-class="add_new" />新增</VButton
        >
        <VButton auth="/goods/basics/images-tag/delete" @click="handleDelete()"
          ><svg-icon class="mr-1 base-red-color" icon-class="del" />删除</VButton
        >
      </template>
    </VTable>
    <ComModal ref="addref" @query="query" :options="options"></ComModal>
    <VLog ref="logRef" :api="getImagesTagLog"></VLog>
  </VPage>
</template>

<script setup lang="jsx" name="BasicsImages-tag">
import { ElMessage, ElMessageBox } from "element-plus";
import ComModal from "./components/ComModal.vue";
import { getOptions } from "@/api/index.js";
import {
  queryImagesTagList,
  deleteImagesTag,
  getImagesTagLog,
  setStausImagesTag,
} from "./api";
import VLog from "@/components/VLog";
import { toRefs } from "vue";
const tableRef = ref();
const addref = ref(null);

const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  rowConfig: {
    height: 70,
  },
  columns: [
    { type: "checkbox", width: "40" },
    { field: "sort", title: "排序", width: 100 },
    { field: "id", title: "标签ID", width: 100 },
    {
      field: "tag_name",
      title: "标签名称",
      width: 120,
    },
    {
      field: "tag_type",
      title: "标签类型",
      width: 100,
      slots: {
        default: ({ row }) => {
          return <div>{filterTagName("tagTypeText", row.tag_type)}</div>;
        },
      },
    },
    {
      field: "permissions_type",
      title: "标签权限",
      width: 120,
      slots: {
        default: ({ row }) => {
          const username = [];
          row.images_tag_permissions.length &&
            row.images_tag_permissions.map((i) => {
              username.push(i.username);
            });
          return (
            <div>
              {row.permissions_type == 1
                ? "所有人"
                : row.permissions_type == 2
                ? username.toString()
                : ""}
            </div>
          );
        },
      },
    },
    {
      field: "tag_status",
      title: "标签状态",
      width: 80,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-switch
                disabled={getAuth("/goods/basics/reference-freight/enable-disable")}
                v-model={row.tag_status}
                active-value={1}
                inactive-value={0}
                row={row}
                before-change={beforeChange}
                onChange={() => changeStatus(row)}
              />
            </div>
          );
        },
      },
    },
    {
      field: "importer_company_name",
      title: "标签颜色",
      width: 80,
      slots: {
        default: ({ row }) => {
          return (
            <div
              class="w-5 h-5 rounded"
              style={`background-color: ${row.tag_color}`}
            ></div>
          );
        },
      },
    },
    {
      field: "score",
      title: "分值",
      width: 80,
      slots: {
        default: ({ row }) => {
          return <div>{row.score}</div>;
        },
      },
    },
    {
      field: "auto_relation",
      title: "自动关联",
      width: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>{filterTagName("ruleTypeText", row.auto_relation?.rule_type)}</div>
              <div>
                {filterImageName("taskPriorityText", row.auto_relation?.task_level)}
              </div>
              <div>{row.auto_relation?.task_type_text}</div>
            </div>
          );
        },
      },
    },
    { field: "image_task_type_id", title: "任务类型ID", width: 100 },
    {
      field: "remark",
      title: "备注",
      showOverflow: "title",
      slots: {
        default: ({ row }) => {
          return <div class="overflow-ellipsis overflow-hidden">{row.remark}</div>;
        },
      },
      width: 160,
    },
    { field: "create_username", title: "创建人", width: 160 },
    { field: "create_time", title: "创建时间", width: 180 },
    { field: "update_username", title: "最近更新人", width: 160 },
    { field: "update_time", title: "更新时间", width: 180 },
    {
      title: "操作",
      fixed: "right",
      width: 140,
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex justify-center">
              <VButton
                auth="/goods/basics/images-tag/edit"
                type="primary"
                link
                onClick={() => open("edit", row.id)}
              >
                编辑
              </VButton>
              <VButton
                auth="/goods/basics/images-tag/add"
                type="primary"
                link
                onClick={() => open("copy", row.id)}
              >
                复制
              </VButton>
              <el-button type="primary" link onClick={() => showLog(row.id)}>
                日志
              </el-button>
            </div>
          );
        },
      },
    },
  ],

  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => queryImagesTagList({ ...form, ...page }),
    },
  },
});
// 列表数据

const query = () => {
  tableRef?.value.query();
};

const data = reactive({
  options: {
    typeList: [],
  },
  formArr: {},
});
const { options, formArr } = toRefs(data);

provide("formArr", formArr);

const filterTagName = (type, val) => {
  const findItem = options.value["assignment.ImagesTag"]?.[0][type].find(
    (i) => i.value == val
  );
  return findItem?.label;
};

const filterImageName = (type, val) => {
  const findItem = options.value["assignment.ImagesAssignment"]?.[0][type].find(
    (i) => i.value == val
  );
  return findItem?.label;
};

const fetchOption = async () => {
  getOptions({
    version: "v1",
    name: ["assignment.ImagesTag", "assignment.ImagesAssignment"],
  }).then((res) => {
    options.value = res.data;
  });
};
fetchOption();

const open = (type, id) => {
  nextTick(() => {
    addref.value.open(type, id);
  });
};

const logRef = ref();
const showLog = (id) => {
  logRef.value.open(id);
};

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

const isHandle = () => {
  const records = getSelectRow();
  return !records.length ? ElMessage.error("请先选择行!") && false : true;
};

const handleDelete = () => {
  const records = getSelectRow().map((i) => i.id);
  if (!isHandle()) return;
  ElMessageBox.confirm("此操作将永久删除该项, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteImagesTag({
      id: records,
    });
    ElMessage.success("删除成功");
    query();
  });
};

const handleCopy = (row) => {};

const beforeChange = (row) => {
  return new Promise((resolve) => {
    ElMessageBox.confirm("是否确认修改当前标签状态?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      return resolve(true);
    });
  });
};

const changeStatus = async (row) => {
  try {
    const res = await setStausImagesTag({
      id: row.id,
      tag_status: row.tag_status,
    });
    ElMessage.success("操作成功");
  } catch (e) {
    throw Error(e);
  }
};

const getAuth = (val) => {
  return !(window.BTN_AUTH || []).includes(val);
};
</script>
